import {
  createUserGroup,
  editUserGroup,
  groupQRcode,
  deleteGroup,
  signoutGroup
} from '../../apis/group';
import {
  checkUpload,
  uploadOSS,
  globalData
} from '../../utils/request';
import {
  getOSSAutograph
} from '../../apis/card';
const app = getApp();

Page({
  data: {
    checked: 1,
    avatar: '',
    groupName: '',
    remark: '',
    groupInfo: {},
    OSSAutograph: {}
  },

  onLoad(options) {
    this.setData({
      ...options,
      showGroupBtn: globalData.checkIn
    });
    this.getOSSAutograph();
    if (options.type === 'admin') {
      wx.setNavigationBarTitle({
        title: '组管理'
      });
    } else if (options.type === 'member') {
      wx.setNavigationBarTitle({
        title: '组信息'
      });
    };
    if (options.type !== 'createGroup') this.getBasicInfo(options.groupId);
  },

  getBasicInfo(id) {
    groupQRcode(id).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        this.setData({
          groupInfo: data,
          groupName: data.title,
          avatar: !new RegExp('https://').test(data.image) && !new RegExp('http://').test(data.image) && data.image !== '' ? app.globalData.url + data.image : data.image,
          checked: data.checked,
          remark: data.remark
        });
      };
    });
  },

  changeConfirm(e) {
    let {
      value
    } = e.detail;
    if (value) {
      this.setData({
        checked: 2
      });
    } else {
      this.setData({
        checked: 1
      });
    };
  },

  selectAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        this.setData({
          avatar: res.tempFilePaths[0]
        });
        // wx.navigateTo({
        //   url: `/pages/tailoring/index?src=${res.tempFilePaths[0]}`
        // });
      }
    });
  },

  handleInput(e) {
    let {
      value
    } = e.detail;
    this.setData({
      groupName: value
    });
  },

  goQRcode() {
    wx.navigateTo({
      url: `/pages/qrCode/index?type=group&groupId=${this.data.groupId}&from=${this.data.from}`
    });
  },

  actionJump(e) {
    let {
      type
    } = e.currentTarget.dataset;
    if (type === 'admin') {
      wx.navigateTo({
        url: `/pages/editGroup/index?type=edit&groupId=${this.data.groupId}`
      });
    } else if (type === 'apply') {
      wx.navigateTo({
        url: `/pages/joinGroupApply/index?type=group&groupId=${this.data.groupId}`
      });
    };
  },

  // OSS签名
  getOSSAutograph() {
    getOSSAutograph().then(res => {
      if (res.data.code === 200) {
        this.setData({
          OSSAutograph: res.data.data
        });
      };
    });
  },

  // 确认
  confirm() {
    if (this.data.groupName === '') {
      wx.showToast({
        title: '请输入组名称',
        icon: 'none'
      });
      return
    };
    if (this.data.type === 'createGroup') {
      if (this.data.avatar === '') {
        this.create();
      } else {
        this.upload();
      };
    } else if (this.data.type === 'admin') {
      if (new RegExp('^wxfile://').test(this.data.avatar) || new RegExp('^http://tmp').test(this.data.avatar)) {
        this.upload();
      } else {
        this.edit(this.data.groupInfo.image);
      };
    };
  },
  // 上传
  upload() {
    wx.showLoading({
      title: '上传中...'
    });
    checkUpload(this.data.avatar).then(res => {
      let {
        code
      } = JSON.parse(res.data);
      if (code === 200) {
        let fileName = globalData.userId + '-' + new Date().getTime() + '.png';
        uploadOSS(this.data.avatar, this.data.OSSAutograph.host, {
          key: `${this.data.OSSAutograph.dir}/${fileName}`,
          policy: this.data.OSSAutograph.policy,
          OSSAccessKeyId: this.data.OSSAutograph.accessid,
          signature: this.data.OSSAutograph.signature,
          success_action_status: '200'
        }).then(res => {
          if (res.statusCode === 200) {
            let avatar = `${this.data.OSSAutograph.host}/${this.data.OSSAutograph.dir}/${fileName}`;
            if (this.data.type === 'createGroup') {
              this.create(avatar);
            } else if (this.data.type === 'admin') {
              this.edit(avatar);
            };
          }
        });
      } else {
        wx.showToast({
          title: '头像违规，请重新上传',
          icon: 'none'
        });
      };
    });
  },
  // 创建
  create(avatar) {
    createUserGroup(this.data.cardId, this.data.groupName, this.data.checked, avatar).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        wx.setStorageSync('selectGroup', JSON.stringify({
          groupId: data
        }));
        wx.showToast({
          title: '创建成功',
          icon: 'success',
          duration: 1500,
          mask: true,
          success: res => {
            let timer = setTimeout(() => {
              wx.switchTab({
                url: '/pages/groupDetails/index'
              });
              clearTimeout(timer);
            }, 1500);
          }
        });
      };
    });
  },

  // 解散或者退出
  dismissSignout() {
    wx.showModal({
      title: this.data.groupInfo.master ? '确定解散该名片组？' : '确定退出该名片组',
      success: res => {
        if (res.confirm) {
          this.data.groupInfo.master ? deleteGroup(this.data.groupId).then(res => {
            if (res.data.code === 200) {
              let pages = getCurrentPages();
              let prevPage = pages[pages.length - 2];
              prevPage.setData({
                from: '',
                groupId: null,
                animationDuration: 0,
                titleTop: 0,
                titleHeight: 0,
                officialGroupSwiper: [],
                officialRecommendGroup: [],
                showModal: false,
                groupInfo: {},
                shareImage: '',
                cardWallList: [],
                cardWallPageNum: 1,
                cardWallTotal: 0,
                cardWallCurrent: 0,
                memberList: [],
                memberPageNum: 1,
                memberNum: 0,
                memberSwiperCurrent: 0,
                groupNoticeShow: false,
                noSelectShow: true
              });
              wx.removeStorage({
                key: 'selectGroup'
              });
              wx.showToast({
                title: '解散成功',
                icon: 'success',
                mask: true,
                duration: 1500,
                success: res => {
                  setTimeout(() => {
                    wx.navigateBack({
                      delta: 1
                    });
                  }, 1500);
                }
              });
            };
          }) : signoutGroup(this.data.groupId, this.data.groupInfo.joinCardId).then(res => {
            if (res.data.code === 200) {
              let pages = getCurrentPages();
              let prevPage = pages[pages.length - 2];
              prevPage.setData({
                from: '',
                groupId: null,
                animationDuration: 0,
                titleTop: 0,
                titleHeight: 0,
                officialGroupSwiper: [],
                officialRecommendGroup: [],
                showModal: false,
                groupInfo: {},
                shareImage: '',
                cardWallList: [],
                cardWallPageNum: 1,
                cardWallTotal: 0,
                cardWallCurrent: 0,
                memberList: [],
                memberPageNum: 1,
                memberNum: 0,
                memberSwiperCurrent: 0,
                groupNoticeShow: false,
                noSelectShow: true
              });
              wx.removeStorage({
                key: 'selectGroup'
              });
              wx.showToast({
                title: '退出成功',
                duration: 1500,
                icon: 'success',
                mask: true,
                success: res => {
                  let timer = setTimeout(() => {
                    wx.navigateBack({
                      delta: 1
                    });
                    clearTimeout(timer);
                  }, 1500);
                }
              });
            };
          });
        };
      }
    });
  },

  // 编辑群公告
  editGroupNotice() {
    wx.navigateTo({
      url: `/pages/editGroupNotice/index?remark=${this.data.remark}`
    });
  },

  // 修改
  edit(avatar) {
    editUserGroup(this.data.groupId, this.data.groupName, this.data.checked, avatar, this.data.remark).then(res => {
      if (res.data.code === 200) {
        wx.showToast({
          title: '已保存',
          icon: 'success',
          mask: true,
          duration: 1500
        });
      };
    });
  }
})